package com.example.demo01.demos.web;

import com.example.demo01.demos.web.dto.MergeRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

@RestController
public class FileUploadController {

    @Value("${upload.path}")
    private String uploadPath;

    // 上传分片
    @PostMapping("/upload")
    public ResponseEntity<String> uploadChunk(
            @RequestParam("file") MultipartFile file,
            @RequestParam("chunkNumber") int chunkNumber,
            @RequestParam("totalChunks") int totalChunks,
            @RequestParam("identifier") String identifier,
            @RequestParam("filename") String filename) throws IOException {

        // 创建上传目录（如果不存在）
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 创建临时目录存放分片
        String tempDir = uploadPath + File.separator + identifier;
        File chunkDir = new File(tempDir);
        if (!chunkDir.exists()) {
            chunkDir.mkdirs();
        }

        // 保存分片文件
        String chunkFilename = chunkNumber + ".part";
        Path chunkPath = Paths.get(tempDir, chunkFilename);
        Files.write(chunkPath, file.getBytes());

        return ResponseEntity.ok("分片上传成功");
    }

    // 合并分片
    @PostMapping("/merge")
    public ResponseEntity<String> mergeChunks(
            @RequestBody MergeRequest mergeRequest) throws IOException {

        String identifier = mergeRequest.getIdentifier();
        String filename = mergeRequest.getFilename();
        int totalChunks = mergeRequest.getTotalChunks();

        String tempDir = uploadPath + File.separator + identifier;
        String outputFilename = filename;

        // 确保文件名唯一，避免覆盖
        File outputFile = new File(uploadPath, outputFilename);
        int counter = 1;
        while (outputFile.exists()) {
            String newFilename = counter + "_" + filename;
            outputFile = new File(uploadPath, newFilename);
            counter++;
        }

        // 创建输出文件
        try {
            Files.createFile(outputFile.toPath());
        } catch (IOException e) {
            return ResponseEntity.badRequest().body("无法创建输出文件");
        }

        // 合并所有分片
        for (int i = 0; i < totalChunks; i++) {
            Path chunkPath = Paths.get(tempDir, i + ".part");
            byte[] chunkBytes = Files.readAllBytes(chunkPath);
            Files.write(outputFile.toPath(), chunkBytes, StandardOpenOption.APPEND);
        }

        // 删除临时目录
        deleteDirectory(new File(tempDir));

        return ResponseEntity.ok("文件合并成功: " + outputFile.getName());
    }

    // 删除目录及其内容
    private void deleteDirectory(File directory) {
        if (directory.exists()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteDirectory(file);
                    } else {
                        file.delete();
                    }
                }
            }
            directory.delete();
        }
    }
}
